package com.hxci.web.controller;

import com.hxci.web.bean.Conn;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class  LoginServlet extends HttpServlet {
    ServletConfig servletConfig;
    @Override
    public void init(ServletConfig config) throws ServletException {
        servletConfig=config;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        boolean flage=false;
        ServletContext ctx=servletConfig.getServletContext();
        String realPath=ctx.getRealPath("/WEB-INF/db.properties");
        String Type = req.getParameter("Type");
        String sql="select * from ";
        if(Type.equals("user")){
            sql+=" user t";
        } else if (Type.equals("admin")) {
            sql+=" admin t";
            flage=true;
        }
        else
            System.out.println("error:Type is"+Type);
        sql+=" where t.login_account= ? and "
                +" t.login_pwd= ? ";
        String login_account=req.getParameter("username");
        String login_pwd=req.getParameter("password");

        ArrayList paramList=new ArrayList();
        paramList.add(login_account);
        paramList.add(login_pwd);

        Conn dbUtil=new Conn(realPath);
        List userList=dbUtil.doQuery(sql,paramList);
        System.out.println("56"+userList);
        if(userList.size()>0){
//            String str="<script>alert('登录成功')</script>";
            HttpSession session=req.getSession();
            resp.getWriter().println("登录成功");
            session.setAttribute("loginc",login_account);
            if(flage) {
                session.setAttribute("login_account","admin");
                resp.sendRedirect("main.jsp");
            }
            else {
                session.setAttribute("login_account","user");
                resp.sendRedirect("user.jsp");
            }
            //重定向
            //req.getRequestDispatcher("login/main.jsp").forward(req,resp);
            //
        }else {
            //弹窗显示
            String str="<script>alert('用户名或密码错误，请重新登录')</script>";
            resp.getWriter().println(str);
        }
    }
}
